<template>
    <div class="box">
    <div class="head">
       <el-row class="headBtn">
        <i :class="rotate ? 'el-icon-refresh rotateGo' : 'el-icon-refresh rotateBack'" @click="shuaxin"></i>
        <el-button type="primary" class="button" @click="add">添加</el-button>
        <el-button type="primary" class="button" @click="deletebatch(sels)">批量删除</el-button>
      </el-row> 
    </div>

    <el-table
        height="73vh"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        ref="multipleTable"
        :data="namelist"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
    <el-table-column
    align="center"
      type="selection"
      prop="roleId"
      width="60">
    </el-table-column>
    <el-table-column
    align="center"
      prop="roleName"
      label="角色名称"
     >
    </el-table-column>
    <el-table-column
    align="center"
      prop="remark"
      label="角色描述"
      :show-overflow-tooltip="true"
      >
    </el-table-column>
    <el-table-column
      align="center"
      label="操作"
      width="200px"
      >
      <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="edit(scope.row)" circle></el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deletebatch(scope.row.roleId)" circle></el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加弹框 -->
 <el-dialog :title="title" :visible.sync="toAdd" width="38%" @closed="closeMyself">
   <div class="roleform">
  <el-form :model="form" >
  <el-form-item label="角色名称：" >
       <el-input type="text"  v-model="form.roleName" autocomplete="off" class="blacknameinput"></el-input>
  </el-form-item>

    <el-form-item label="角色描述：" >
      <el-input type="textarea" :rows="5" v-model="form.remark" autocomplete="off" class="blacknameinput"></el-input>
    </el-form-item>

    <el-form-item label="权限操作：">    
        <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> 
        <div class="cds">
            <div class="cds1-1">
                <p>菜单树</p>
            </div>
       <el-tree
        :data="organizationData"
        ref="tree"
        show-checkbox
        default-expand-all
        node-key="id"
        :props="defaultProps">
   </el-tree>
   </div>
  </el-form-item>
    </el-form>
    </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save">保 存</el-button>
    <el-button @click="closeMyself">取 消</el-button>
  </div>
</el-dialog>

<!-- 分页 -->
 <div class="bottonpage">
    <el-pagination background @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                  :current-page="current" 
                  :page-sizes="[10, 20, 50, 100]" 
                  :page-size="size"
                  layout="prev, pager, next, jumper , slot, total" 
                  :total="total" class="pageInfo">
      <span id="sure">确定</span>
    </el-pagination>
 </div>
    </div>
</template>

<script>
import { axiosRequest } from "@/utils/axiosRequest";
export default {
    data(){
        var userInfo = JSON.parse(window.sessionStorage.getItem('userInfo')).user
        return{
          rotate: false,
          userName: userInfo.empName,
          namelist:[],
          form:{
               roleName:'',
               remark:''
             },
          checkAll: false,
          current: 1,
          size:10,
          total:0,
          title:'',
          // 可以根据接口返回数据展示
          organizationData: [],
          // children和label 与接口字段保持一致
          defaultProps: {
              children: 'children',
              label: 'menuName'
          },
          // formLabelWidth: '20%',
          toDelete:false,
          toAdd:false,
          rids:'',
        }
    },
    methods: {

      // 添加弹窗的保存按钮
      save(){
         if(this.form.roleName!=''){
         this.addrole();
          // this.sysRoles();
          }else{
            this.$message({
              type:'warning',
              message:'请输入角色名称！'
            })
            return
          }
          this.form.roleName=''
          this.form.remark=''
          this.toAdd=false
      },

      //保存——添加或者编辑角色，权限选择
      addrole(){
          var rad=''
          var ridsa = this.$refs.tree.getCheckedKeys().join(',')// 获取当前的选中的数据[数组] -id, 把数组转换成字符串
          var checkedKeys  = this.$refs.tree.getCheckedNodes()// 全选
          var halfKeys=this.$refs.tree.getHalfCheckedNodes()//半选(即使只选子节点也把父节点也选中)
          var save=checkedKeys.concat(halfKeys)
          save.forEach( ids => {//获取选中的所有的父级id
            rad+=','+ids.id
          })
          rad=rad.substr(1) // 删除字符串前面的','
          var rids=rad+','+ridsa
          var arr=rids.split(',')//  把字符串转换成数组
          arr=[...new Set(arr)]; // 数组去重
          rids=arr.join(',')// 把数组转换成字符串
          this.rids=rids
          // console.log(this.rids)
          let addForm ={
            roleId:this.form.roleId,
            roleName:this.form.roleName,
            remark:this.form.remark,
            rolePrivstr:this.rids
          }
          let newDigi = '';
          newDigi = this.namelist.find( e => {
              return e.rolePrivstr.length === addForm.rolePrivstr.length
          })
          if(newDigi !== undefined){
            this.$alert('数据中已有一个角色拥有该权限，不需重复添加！', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                this.$message({
                  type: 'info',
                  message: ` 确定信息！！！ `
                });
              }
            });
            return;
          }
          axiosRequest("post", "/roles/addRole", addForm).then((res) => {
              if (res.data.code === 200) {
                    this.$message({
                      type: 'success',
                      message:this.title+'成功!'
                      });
                      this.list();
                    } else {
                      this.$message.error(res.data.data);
                    }
              });
      },

      // 当选择项发生变化时会触发该事件 table表的多选或者单选
      handleSelectionChange(sels) {
        this.sels = sels;
      },

      // 分页查询
      current_change(current){
            this.current=current;
            // console.log(this.current)
            this.list()
      },

      // 请求后台，获取到角色列表
      list(){
        //  console.log(this.userName)
          let listForm ={
            current:this.current,
            size:this.size
          }
          axiosRequest("get", "/roles/list", listForm).then((res) => {
              //  console.log(res)
              this.total=res.data.page.total
              this.current=res.data.page.current;
              this.size=res.data.page.size;
                if (res.data.code === 200) {
                  this.namelist= res.data.data;
                } else {
                  this.$message.error(res.data.data);
                }
            });
      },

      //点击刷新图标按钮
      shuaxin(){
        var self = this;
        if(self.rotate == false){
          self.rotate = true;
        }else {
          self.rotate = false;
        }
        self.list();
        self.$message({
          showClose: true,
          message: '刷新成功！！！',
          type: 'success'
        });
      },

      // 添加弹窗的模态框
      add(){
          this.title='添加角色'
          this.gettrees()
          this.toAdd=true
      },

      //点击编辑按钮图标
      edit(row){
          this.title='编辑角色'
          this.toAdd=true
          this.form=row
          console.log(row)
          //遍历数组生成新的对象数组
          let privstrlist= row.rolePrivstr.split(",")
          let obj={}
          let objlist=[]
          for(let i in privstrlist){
            obj={id:privstrlist[i]}
            objlist.push(obj)
          }
          // 解决方法: this.$nextTick()，this.$nextTick()会在dom更新之后在执行回调
          this.$nextTick(function(){
              this.$refs.tree.setCheckedNodes(objlist);
          }) 
      },

      // 关闭添加弹窗，清空数据
      closeMyself(){
        this.form={}
        this.checkAll=false
        this.$nextTick(function(){
            this.$refs.tree.setCheckedNodes([]);
        }) 
        this.toAdd=false
      },

      //批量删除
      //删除单条记录
      deletebatch(roleId){
        let idList=[];
        if(!Array.isArray(roleId)){
            idList.push(roleId)
        }else{
            let ids=this.sels.map(item => item.roleId).join()
            idList=ids.split(",")
         }
          let deleteform ={
            idList: idList
          }
          // console.log(idList)
          //删除提示框
          if(idList!=''){
            if(idList!=1){
              this.$confirm('此操作将永久删除当前选中角色, 是否继续?',  '提示', {
              confirmButtonText:  '确定',
              cancelButtonText: '取消',
              type: 'warning'
              }).then(()  => {
              axiosRequest("delete",  "/roles/del",deleteform).then((result)  =>  {
               if  (result.data.code === 200) {
                  this.$message({
                    type: 'success',
                    message:  '删除成功!'
                    });
                  this.list();
                  } else {
                  this.$message.error(result.data.data);
                  }
                  })
              }).catch(() => {
                  this.$message({
                type: 'info',
                message: '已取消删除'
              });
              })}else{
               this.$message({
                      type: 'warning',
                      message:'不能删除管理员！'
                    })
            }
              }else{
                    this.$message({
                      type: 'warning',
                      message:'请选择要删除的记录！'
                    })
              }
      },

      // 弹窗 ——选择所有权限
      handleCheckAllChange(){
        if (this.checkAll) {
            this.$refs.tree.setCheckedNodes(this.organizationData);
        } else {
            this.$refs.tree.setCheckedKeys([]);
        }
      },

      //每页显示
      handleSizeChange(val) {
        this.size = val;
        this.current=1;
        this.list()
      },

      //显示页
      handleCurrentChange(val) {
        this.current = val;
        this.list();
      },
    
      //请求后台的方法-需要显示页面的权限
      gettrees(){
          axiosRequest("get", "/menu/list-all",null).then((result) => {
            if (result.data.code === 200) {
                  //console.log(result)
                  this.organizationData=result.data.data
                } else {
                this.$message.error(result.data.data);
                  }
              })
      }
 },
  mounted: function() {
      this.list();
      this.gettrees();
     }
    
}
</script>

<style lang="less" scoped>
 .button{
      padding: 8px 11px;
    }
.box{
  width: 100%;
  height: 100%;
  padding: 0px 10px;
}
.head{
    width: 100%;
    margin-bottom: 3.5vh;
}

.el-icon-refresh {
  margin-left: 2%;
}

.el-icon-refresh:hover {
  color: #218ef3;
  cursor:  pointer;
}

.rotateBack {
  transform: rotate(180deg);
  transition: all 2s;
}

.rotateGo {
  transform: rotate(-180deg);
  transition: all 2s;
}

.headBtn > .el-button {
  margin-top: 4px;
  margin-left: 4%;
}

img{
    float: left;
    margin-right: 5%;
    cursor: pointer;
}
.titleColor{
  color: red;
}
.blacknameinput{
  width: 70% ;
}
.roleform{
  margin-left: 8%;
}
.cds{
    margin-left: 13%;
    border: 1px rgba(0, 0, 0, 0.089) solid;
    width: 70%;
    overflow: auto;
    height: 25vh;
   
}
.cds::-webkit-scrollbar {
    display: none;
}
.cds1-1{
    background: rgba(0, 0, 0, 0.048);
}
.cds1-1 p{
margin-left: 3%;
}
.bottonpage{
  height: 4vh;
  bottom: 4vh;
  position: absolute;
}
.contents-head{
  height: 72vh; 
  overflow: auto;
}

.el-table td, .el-table th {
    text-align: center;
}

#sure {
  border: 1px solid #DCDFE6;
  text-align: center;
  line-height: 25px;
  display: inline-block;
  margin: 0px 15px;
  cursor: pointer;
  width: 4%;
  border-radius: 3px;
}
</style>